package indi.zhifa.study2024.nbr.monitor.logic.curd.login.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import indi.zhifa.core.auth.util.ITokenUtil;
import indi.zhifa.core.common.web.entity.exception.ServiceException;
import indi.zhifa.study2024.common.auth.token.AuthObject;
import indi.zhifa.study2024.common.auth.token.TokenObjectOuterClass;
import indi.zhifa.study2024.nbr.monitor.gen.monitor.user.po.GenMonitorEnterpriseEntity;
import indi.zhifa.study2024.nbr.monitor.gen.monitor.user.po.GenMonitorUserEntity;
import indi.zhifa.study2024.nbr.monitor.gen.monitor.user.po.json.RoleInfo;
import indi.zhifa.study2024.nbr.monitor.gen.monitor.user.service.IGenMonitorEnterpriseDbService;
import indi.zhifa.study2024.nbr.monitor.gen.monitor.user.service.IGenMonitorUserDbService;
import indi.zhifa.study2024.nbr.monitor.logic.curd.login.service.ILoginService;
import indi.zhifa.study2024.nbr.monitor.logic.curd.login.entity.request.LoginRequest;
import indi.zhifa.study2024.nbr.monitor.logic.curd.login.entity.response.LoginResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Base64;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Component
public class LoginServiceImpl implements ILoginService {

    private final IGenMonitorUserDbService mMonitorUserDbService;
    private final IGenMonitorEnterpriseDbService mMonitorEnterpriseDbService;
    private final PasswordEncoder mPasswordEncoder;
    private final ITokenUtil mTokenUtil;
    private final FastJsonConfig mFastJsonConfig;

    @Override
    public LoginResponse login(LoginRequest pLoginRequest) {

        GenMonitorUserEntity monitorUserEntity = mMonitorUserDbService.findByUserName(pLoginRequest.getUsername());
        if(null == monitorUserEntity) {
            throw new ServiceException("没有找到名为"+pLoginRequest.getUsername()+"的用户名");
        }
        String encodePasswd = monitorUserEntity.getPasswd();
        if(!mPasswordEncoder.matches(pLoginRequest.getPassword(), encodePasswd)) {
            throw new ServiceException("密码错误");
        }
        GenMonitorEnterpriseEntity enterpriseEntity = mMonitorEnterpriseDbService.findByEnpCode(monitorUserEntity.getEnpCode());

        TokenObjectOuterClass.TokenObject tokenObject = TokenObjectOuterClass.TokenObject.newBuilder()
                .setEnpId(enterpriseEntity.getId())
                .setEnpCode(enterpriseEntity.getEnpCode())
                .setEnpName(enterpriseEntity.getEnpName())
                .setUserId(monitorUserEntity.getId())
                .setUserName(monitorUserEntity.getUserName())
                .setNickName(monitorUserEntity.getNickName())
                .addAllRoles(monitorUserEntity.getRoles().stream().map(RoleInfo::getCode).collect(Collectors.toList()))
                .setServId(enterpriseEntity.getServCode())
                .setDbCode(enterpriseEntity.getDbCode()).build();
        String token = mTokenUtil.encrypt(tokenObject);

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token);
        loginResponse.setUserInfo(monitorUserEntity);
        loginResponse.setEnterpriseInfo(enterpriseEntity);

        return loginResponse;
    }

    @Override
    public String decodeTokenToAuthStr(String pToken) {
        AuthObject authObject = mTokenUtil.decrypt(pToken);
        byte[] jsonBytes = JSON.toJSONBytes(authObject,mFastJsonConfig.getWriterFeatures());
        String base64Str = Base64.getUrlEncoder().encodeToString(jsonBytes);
        return base64Str;
    }
}
